from django.http import *
from django.forms import ModelForm
from django.template import *
from django.shortcuts import *
from django.template.loader import get_template
from l2l.apps.usermanagement.forms import *
from django.core.mail import send_mail
from l2l.apps.usermanagement.models import *
from django.contrib.auth import authenticate, login
from django.middleware import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import get_hexdigest, check_password
from django.utils import simplejson
from django.core.serializers import serialize
import json
from django.conf import settings
#from django.contrib.sessions.models import Session

def home_page(request):
	variables=RequestContext(request,{'user': request.user,'request':request} )
	return render_to_response('pages/home.html',variables )	
	
def searchAttorney(request):
	search_attorney=request.POST["searchtext"]
	rawqry='%s%s%s%s%s'%('select a.* from usermanagement_userprofile a,auth_user b where a.user_id_id=b.id and (b.first_name like "%%',search_attorney,'%%" or b.last_name like"%%',search_attorney,'%%")and a.user_type=1 and a.verified=1 and visible_in_search=1')
	#rawqry='select * from usermanagement_userprofile where user_id_id<100'
	results=userprofile.objects.raw(rawqry)
	variables=RequestContext(request,{'title':'Search Results','attorneys':results,'searchtxt':search_attorney})
	return render_to_response('user/attorney_search.html',variables )	
   	#return HttpResponse(rawqry)	
   	
   	
def searchAttorney11(request):
	from l2l.apps.lawschool.models import *
	rr='select * from lawschool_lawschool'
	r=lawschool.objects.raw(rr)
	variables=RequestContext(request,{'attorneys':r})
	return render_to_response('user/attorney_search.html',variables )	
   	#return HttpResponse(r)	
   	
def sendVerification(request):
	
	#licenceno=request.POST['licence'];
	licenceno='1000025'
	try:
		from django.core import serializers
		usrprofile=userprofile.objects.get(licence=licenceno,old_imported=1);
		#usrprofile=serialize('json',usrprofile)
		response={'licence_exists':True,'userinfo':usrprofile};
	except ObjectDoesNotExist:	
		response={'licence_exists':False};
	#response=serialize('json', response)
	#jsondata = json.dumps({"c": 0, "b": 0, "a": 0}) 
	#sondata=json.dumps(response)   
	response= Session.objects.aggregate(Max('date'), Min('date'))
 
	return HttpResponse(simplejson.dumps(simplejson.loads(serialize('json', response,ensure_ascii=False)))
)
   
   
def register_page(request):
	if request.method == 'POST':
		form1 = UserProfileForm(request.POST)
		form2 = RegistrationForm(request.POST)
		
		if form1.is_valid() and form2.is_valid():
			#saving user in auth_user table
			try:
				
				usr = User.objects.create_user(username=form2.cleaned_data['username'],password=form2.cleaned_data['password'],email=form2.cleaned_data['email'])
				usr.first_name=form2.cleaned_data['first_name']
				usr.last_name=form2.cleaned_data['last_name']
				usr.is_active=False
				usertype=form1.cleaned_data['user_type']
				usr.groups.add(usertype) # add by id(Attorney)
				usr.save()
				#form1.user_id=usr.id
				usrpf=form1.save()
				#form1.cleaned_data['user_id']=usr			
				#return HttpResponse(form1.user_id)
				usrprofile=userprofile.objects.get(pk=usrpf.id)
				usrprofile.user_id=usr
				usrprofile.verification_code=getRamdomCode(999999999)
				usrprofile.save()
				title="Registration Succeeded!!"
				message="You are successfully registered,Please Verify Your account from your email to complete registration.Thank you"
				variables = RequestContext(request,{'title':title,'message':message})
				email='themaheshe1@gmail.com'
				addlink='%s%s%s'%('<a href="http://localhost:8000/l2l/users/verification/',userprofile.verification_code,'>Verify Your L2L Account,click here.</a>')
				email_message='%s%s'%('You have been Successfully registered to L2L.com.Please click link below to verify Your account',addlink)
				send_mail('L2L Registration',email_message, 'no-reply@lawyertolawyerny.com',[email], fail_silently=False)
				return render_to_response('pages/success_page.html',variables)
				
			except:
				title="Registration Failed,couldnot save!!"
				message="Try again!!"	
				variables = RequestContext(request,{'form1': form1,'form2':form2,'title':title,'message':message})
				return render_to_response('user/registration.html',variables)
		else:
			errs1=form1.errors
			errs2=form2.errors
			errs='%s%s'%(errs1,errs2)
			#form = RegistrationForm()
			variables = RequestContext(request,{'form1': form1,'form2':form2,'message':errs})
			return render_to_response('user/registration.html',variables)	
	else:
		form2 = RegistrationForm()
		form1 =  UserProfileForm()
		variables = RequestContext(request,{'form1': form1,'form2':form2,'message':'Fill up this registration form'})
		return render_to_response('user/registration.html',variables)


def userVerification(request,verificationCode):
	#try:
	usrprofile=userprofile.objects.get(verification_code=verificationCode)
	usrprofile.verified=1
	usrprofile.save()
	user=User.objects.get(pk=int(usrprofile.user_id.id))
	user.is_active=True
	user.save()
	message="User Successfully Verified.Welcome to L2L"
	user = User.objects.get(pk=usrprofile.user_id.id,is_active=True)
	user.backend = 'django.contrib.auth.backends.ModelBackend'
	login(request,user)	
	variables = RequestContext(request,{'message':message,'user': user,'title':'Dashboard'} )
	#except:
		#message="Verification Failed!!"	
	#return render_to_response('pages/home.html',variables)	
	
	return render_to_response('user/dashboard.html',variables)  

def getRamdomCode(code_range):
	return random.randrange(code_range)

def register_page1(request):
	if request.method == 'POST':
		form = RegistrationForm(request.POST)
		if form.is_valid():
			#saving user in auth_user table
			user = User.objects.create_user(username=form.cleaned_data['username'],password=form.cleaned_data['password1'],email=form.cleaned_data['email'])
			usertype=form.cleaned_data['user_type']
			user.groups.add(usertype) # add by id(Attorney)
			user.first_name=form.cleaned_data['first_name']
			user.last_name=form.cleaned_data['last_name']
			email=user.email			
			user.save()
			#saving user profile details in child-table
			licence=form.cleaned_data['licence']
			phone=form.cleaned_data['phone']
			address=form.cleaned_data['address']
			city=form.cleaned_data['city']
			target_graduation_date=form.cleaned_data['graduation_date']
			visible_in_search=form.cleaned_data['Visible_in_search']		
			user_type=form.cleaned_data['user_type']
			dat= userprofile(licence=licence,user_type=user_type,phone=phone,address=address,city=city,target_graduation_date=target_graduation_date,visible_in_search=visible_in_search,user_id=user)
			dat.save()
			#send_mail('L2L Registration','You have been Successfully registered to L2L.com', 'admin@l2l.com',[email], fail_silently=False)
			#send_mail('Successfully registered to Windtrader', 'User registered',user.username,['themaheshe1@gmail.com'])
			#return render_to_response('main_page.html',{ 'user': request.user } )
			variables = RequestContext(request,{'title':'Registration Succeeded!!','message':'You are successfully registered,Thank you'})
			return render_to_response('pages/success_page.html',variables)
		else:
			errs=form.errors
			form = RegistrationForm()
			variables = RequestContext(request,{'form': form,'message':errs})
			return render_to_response('user/registration.html',variables)	
	else:
		form = RegistrationForm()
		variables = RequestContext(request,{'form': form,'message':'Fill up this registration form'})
		return render_to_response('user/registration.html',variables)	


def register_facebook(request):
	if request.method=='POST':
		fb_id 	    = request.POST["id"]
		username	= request.POST["username"]
		firstname	= request.POST["firstname"]
		lastname	= request.POST["lastname"]
		email		= request.POST["email"]		
		
		N=12
		#fb_id= '100001778104032'
		#username='blow_flower2001@yahoo.com'
		#firstname='rojina'
		#lastname='karki'
		#email='blow_flower2001@yahoo.com'
		
		password = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
		request.session["fb_user_passsword"] = password
		request.session["fb_user_email"] = email
					
		try:
			user = User.objects.get(email = email,is_active=True)
			user.backend = 'django.contrib.auth.backends.ModelBackend'
			login(request,user)
			
			
			return HttpResponse('/l2l/users/dashboard/')

		except ObjectDoesNotExist:
			try:
				user = User.objects.get(email = email)
				request.session["message"] = "Account already exists and is inactive. Verify via email."
				return HttpResponse('/')
			except:
				if request.session["fb_user_id"]:
					#del request.session["fb_user_id"]
					form1 =  UserProfileForm()
					variables = RequestContext(request,{'form1': form1,'message':'Required for Registration'})
					#return render_to_response('user/fb_registration.html',variables)
					return HttpResponse('/l2l/users/fbsave/')
				else:
					user = User.objects.create_user(username=email,password=password,email=email)
					user.first_name=firstname
					user.last_name=lastname
					user.is_active=False
					#usertype=form1.cleaned_data['user_type']
					#user.groups.add(usertype) # add by id(Attorney)
					user.save()		
					request.session["fb_user_id"] = user.id				
					#form2 = RegistrationForm()
					form1 =  UserProfileForm()
					form1.user_id=user
					variables = RequestContext(request,{'form1': form1,'message':'Required for Registration'})
					#return render_to_response('user/fb_registration.html',variables)
					return HttpResponse('/l2l/users/fbsave/')
			
					
				
				
def saveFbAddtionalInfo(request):
	if request.method == 'POST':
		form1 = UserProfileForm(request.POST)	
		
		if form1.is_valid() :
			#saving user in auth_user table
			#try:	
				usr=User.objects.get(email=request.session["fb_user_email"])
				usr.is_active=True
				usertype=form1.cleaned_data['user_type']
				usr.groups.add(usertype) # add by id(Attorney)
				usr.save()
				
				usrpf=form1.save()
				usrprofile=userprofile.objects.get(pk=usrpf.id)
				usrprofile.user_id=usr
				usrprofile.verified=1
				usrprofile.address2=request.session["fb_user_passsword"]
				usrprofile.save()
				password=request.session["fb_user_passsword"]
				#email=request.session["fb_user_email"]
				email='themaheshe1@gmail.com'
				#sending login credentials to the user
				try:
					emailmsg = "Your registration details from facebook are as follows : <br /> Logging URL : http://localhost:8000/l2l/users/login/ <br /> Username : %s <br /> Password : %s <br />" % (email,password)
					msg=EmailMessage('You have successfully regestered to L2L App with Facebook credentials.',emailmsg,settings.DEFAULT_FROM_EMAIL,[email])
					msg.content_subtype="html"
					msg.send()
					registration_status = 1
					
				except:
					registration_status = 0
				
				#auto- login for fb users
				email=request.session["fb_user_email"]
				user = User.objects.get(email = email,is_active=True)
				user.backend = 'django.contrib.auth.backends.ModelBackend'
				login(request,user)
				#redirect to his/her dashboard
				title="Registration Succeeded!!"
				message="You are successfully registered using Your Facebook Login.Please check Your email for your Login Credentials,Thank you."
				variables = RequestContext(request,{'title':title,'message':message,'user':user})
				#try:
				del request.session["fb_user_email"] 
				del request.session["fb_user_passsword"] 
				del request.session["fb_user_id"]
				#except KeyError:
					
				return render_to_response('user/dashboard.html',variables)
							
			#except:
				#title="Registration Failed,couldnot save!!"
				#message="Try again!!"	
				#variables = RequestContext(request,{'form1': form1,'title':title,'message':message})
				#return render_to_response('user/fb_registration.html',variables)
		else:
			errs=form1.errors
			
			#form = RegistrationForm()
			variables = RequestContext(request,{'form1': form1,'message':errs})
			return render_to_response('user/fb_registration.html',variables)	
	else:
		form1 =  UserProfileForm()
		variables = RequestContext(request,{'form1': form1,'message':'Continue Registration Using Facebook Login info'})
		return render_to_response('user/fb_registration.html',variables)
		#return HttpResponse("Facebook registration successful")
	

@login_required
def editUserProfile(request):
	a=User.objects.get(pk=request.user.id)
	b=userprofile.objects.get(user_id=a.id)
	if request.method == 'POST':
		form2 = RegistrationFormedit(request.POST,instance=a)
		form1= UserProfiledit(request.POST,instance=b)
		if form2.is_valid():			
			#updating user info
			form2.save()
			
			if form1.is_valid():
				#updating user profile details in child-table
				form1.save()
				
			#send_mail('Successfully registered to Windtrader', 'User registered',user.username,['themaheshe1@gmail.com'])
			#return render_to_response('main_page.html',{ 'user': request.user } )
			variables = RequestContext(request,{'title':'Profile Updated','message':'Your Profile has successfully been updated,Thank you'})
			return render_to_response('pages/success_page.html',variables)
			#return render_to_response('registration/success_page.html',{'message':'You are successfully registerd,Thank you'})
		else:
			errs1=form1.errors
			errs2=form2.errors
			errs='%s%s'%(errs1,errs2)
			form2 = RegistrationFormedit(instance=a)
			form1=UserProfiledit(instance=b)
			variables = RequestContext(request,{'form1': form1,'form2': form2,'message':errs})
			return render_to_response('user/editprofile.html',variables)
			
	else:
		
		form2 = RegistrationFormedit(instance=a)
		form1=UserProfiledit(instance=b)
		variables = RequestContext(request,{'form1': form1,'form2': form2,'message':'Your Profile'})
		return render_to_response('user/editprofile.html',variables)
	
def userLogin(request):
    if not request.user.is_authenticated():
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            if user is not None:
				if user.is_active:
					login(request, user)
					variables = RequestContext(request,{ 'loginmessage': 'Successfully logged in' ,'user': request.user} )
					return showDashboard(request)
				else:
					variables = RequestContext(request,{'title':'User is not verfied Yet,Please Verify your account form your Email!','message': 'Inactive Username or Password !! Try Again..' ,'user': request.user} )
					return render_to_response('user/login.html',variables)	
                    
            else:
                variables = RequestContext(request,{'title':'Login Failed!','message': 'Invalid Username or Password !! Try Again..' ,'user': request.user} )
                return render_to_response('user/login.html',variables)
                #return HttpResponse(str('fail'))
        else:
            variables = RequestContext(request,{ 'title':'User Login','message': 'Please Enter Correct Login information Below','user': request.user} )
            return render_to_response('user/login.html',variables)    
    else:
        return showDashboard(request)   

def userLogout(request):
    logout(request)
    return HttpResponseRedirect('/')   
      
@login_required
def showDashboard(request):
	try:
		variables = RequestContext(request,{'title':'User Registration','message': request.session["message"]})
		del request.session["message"] 
	except KeyError:
		variables = RequestContext(request,{'message':'Welcome to L2L','user': request.user,'title':'Dashboard'} )
	return render_to_response('user/dashboard.html',variables)  
   
@login_required
def changePassword(request):
	#form = RegistrationForm(request.POST)
	if request.method == 'POST':
		a=User.objects.get(pk=request.user.id)
		b=userprofile.objects.get(user_id=a.id)
		oldpassword = request.POST['oldpassword']
		newpassword = request.POST['newpassword']
		cnewpassword = request.POST['cnewpassword']
		#user = authenticate(password=oldpassword)
		if a.check_password(oldpassword): 
			if newpassword == cnewpassword:
				#user = User.objects.create_user(username=a.username,password=request.POST['password1'],email=a.email)
				algo = 'sha1'
				salt = get_hexdigest( algo, str(random.random()), str(random.random()))[:5]
				hsh = get_hexdigest( algo, salt, newpassword)
				newpassword = '%s$%s$%s' % ( algo, salt, hsh )
				a.password = newpassword
				a.save()
				variables = RequestContext(request,{'title':'SUCCESS MESSAGE','message':"Password Updated Successfully!. Thank You."})
				return render_to_response('pages/success_page.html',variables)	
			else:
				variables = RequestContext(request,{'message':"Your Password and Confirmation Password doesn't match"})
				return render_to_response('user/change_password.html',variables)
		else:
			variables = RequestContext(request,{'title':'Err','message':"Your Existing Password doesn't match"})
			return render_to_response('user/change_password.html',variables)
		
	else:
		#form = UserPasswordedit()
		variables = RequestContext(request,{'title':'Edit Password','message':'Change Your Password,Make it secure!'})
		return render_to_response('user/change_password.html',variables)
	   